package it.koutifaris.travianmap.dal.sqlservices;

import static it.koutifaris.travianmap.dal.sqlservices.Auditable.COLUMN_NAME_REVISION_ID;
import static it.koutifaris.travianmap.dal.sqlservices.MapSqlContract.Villages.COLUMN_NAME_OWNER_ID;
import static it.koutifaris.travianmap.dal.sqlservices.MapSqlContract.Villages.COLUMN_NAME_POPULATION;
import static it.koutifaris.travianmap.dal.sqlservices.MapSqlContract.Villages.COLUMN_NAME_VILLAGE_ID;
import static it.koutifaris.travianmap.dal.sqlservices.MapSqlContract.Villages.COLUMN_NAME_VILLAGE_NAME;
import static it.koutifaris.travianmap.dal.sqlservices.MapSqlContract.Villages.COLUMN_NAME_X;
import static it.koutifaris.travianmap.dal.sqlservices.MapSqlContract.Villages.COLUMN_NAME_Y;
import static it.koutifaris.travianmap.dal.sqlservices.MapSqlContract.Villages.TABLE_NAME;
import junit.framework.Assert;
import android.content.ContentValues;
import android.database.SQLException;

public class VillagesTableTest extends AbstractMapDbTest {

	public void testUniqueConstraint() {
		ContentValues contentValues = new ContentValues();

		setUniqueKeyData(contentValues);
		setVillageData(contentValues);

		getDbHelper().getWritableDatabase().insertOrThrow(TABLE_NAME, null, contentValues);
		try {
			changeVillageData(contentValues);
			getDbHelper().getWritableDatabase().insertOrThrow(TABLE_NAME, null, contentValues);

			Assert.fail("Unique key on " + COLUMN_NAME_REVISION_ID + " and " + COLUMN_NAME_VILLAGE_ID + " expected");
		} catch (SQLException e) {
			// OK, test passed
		}

	}

	private void setVillageData(ContentValues contentValues) {
		contentValues.put(COLUMN_NAME_OWNER_ID, 1);
		contentValues.put(COLUMN_NAME_POPULATION, 100);
		contentValues.put(COLUMN_NAME_VILLAGE_NAME, "Test Village");
		contentValues.put(COLUMN_NAME_X, 10);
		contentValues.put(COLUMN_NAME_Y, 15);
	}

	private void setUniqueKeyData(ContentValues contentValues) {
		contentValues.put(COLUMN_NAME_REVISION_ID, 1);
		contentValues.put(COLUMN_NAME_VILLAGE_ID, 1);
	}

	private void changeVillageData(ContentValues contentValues) {
		contentValues.put(COLUMN_NAME_OWNER_ID, 2);
		contentValues.put(COLUMN_NAME_POPULATION, 200);
		contentValues.put(COLUMN_NAME_VILLAGE_NAME, "Test Village B");
		contentValues.put(COLUMN_NAME_X, 20);
		contentValues.put(COLUMN_NAME_Y, 25);
	}
}
